﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
using System.IO;
using System.Threading;
using System.Xml;
//using GooglePlusLib;

namespace Camera
{
    public partial class Main : Form
    {
        
        public static String urlPicturebox = "";
        public static Bitmap image;
        public static Bitmap preImage;
        Image image1 = null;
        List<string> files = new List<string>();
        private VideoCaptureDevice Finalvideosource;
        public FilterInfoCollection Vidoedevices;

        int X = 0;
        string p="c:\\";
        string f="jpg";

        string appPath = Path.GetDirectoryName(Application.ExecutablePath);
        System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer();
        int intselectedindex;
        Boolean video = false;

        public Main()
        {
            InitializeComponent();
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            delPic.Visible = false;
            buttonSave.Visible = false;
            Formats.SelectedIndex = 0;
            p = openFileDialog1.InitialDirectory =
                     Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            this.Size = new System.Drawing.Size(pictureBox1.Width+100, 605);
            startVideo();

        }



        void Vidoedevice_newframe(object sender, NewFrameEventArgs eventargs)
        {
            image = (Bitmap)eventargs.Frame.Clone();

            if (chkFlipHorizontal.Checked == true)
            {
                image.RotateFlip(RotateFlipType.RotateNoneFlipX);
            }
            if (chkFlipVertical.Checked == true)
            {
                image.RotateFlip(RotateFlipType.RotateNoneFlipY);
            }

            pictureBox1.Image = image;
        }



        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Exit();

        }

        private void Exit()
        {
            
            stopVideo();
            StreamWriter Str = new StreamWriter(appPath + "\\Setting.ini");
            Str.WriteLine(p);
            Str.WriteLine(f);
            Str.Close();
            Application.Exit();
        }

        private void stopVideo()
        {
            video = false;
            if (Finalvideosource != null && Finalvideosource.IsRunning)
            {
                Finalvideosource.SignalToStop();
                Finalvideosource.WaitForStop();
                Finalvideosource.Stop();
                Finalvideosource = null;
            }
        }
        private void startVideo()
        {
            video = true;
            if (File.Exists(appPath + "\\Setting.ini"))
            {
                StreamReader Str = new StreamReader(appPath + "\\Setting.ini");
                string s = Str.ReadLine();
                string ff = Str.ReadLine();
                if (p == s)
                {

                }
                else
                {

                    p = s;
                    if (p == "C:\\")
                    {
                        p = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);

                    }
                    if (f == ff)
                    { }
                    else
                    {
                        f = ff;

                    }

                }
                Str.Close();
            }
            else
            {

            }
            Random rand = new Random();
            X = rand.Next(0, 1000);

            try
            {
                Vidoedevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

                try
                {
                    foreach (FilterInfo device in Vidoedevices)
                    {
                        comboBox1.Items.Add(device.Name);
                    }
                    comboBox1.SelectedIndex = 0;
                    Finalvideosource = new VideoCaptureDevice(Vidoedevices[comboBox1.SelectedIndex].MonikerString);

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Sorry there is no camera Found\n" + ex.Message);
                }
                PhotoPlace.Text = p;
            }
            catch (Exception ex)
            {
                MessageBox.Show(" no camera Found\n" + ex.Message);
            }
            Finalvideosource.NewFrame += new NewFrameEventHandler(Vidoedevice_newframe);
            Finalvideosource.Start();
            check();
            PhotoPlace.Text = p;
        }

        private void TakePic()
        {
           
            
                myPlayer.SoundLocation = appPath + "\\camera.wav";
                myPlayer.Play();

                listView1.Items.Clear();
                imageList1.Images.Clear();
                image1 = (Image)image.Clone();

                if (image1 == null)
                {
                }

                else
                {
                    if (f.ToLower() == "jpg")
                    {
                        image1.Save(p + "\\picture" + X + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

                    }
                    else if (f.ToLower() == "bmp")
                    {

                        image1.Save(p + "\\picture" + X + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                    }

                    X++;
                }

                image1 = null;

                loadimages();
            
        }

        private void Setting()
        {

            if ((Finalvideosource != null) && (Finalvideosource is VideoCaptureDevice))
            {
                try
                {
                    ((VideoCaptureDevice)Finalvideosource).DisplayPropertyPage(this.Handle);
                }
                catch (NotSupportedException)
                {
                    MessageBox.Show("The video source does not support configuration property page.", "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void About()
        {
            About A = new About();
            A.Show();
        }

        private void About_Click(object sender, EventArgs e)
        {
            About a = new About();
            a.Show();
        }
       
        private void open()
        {
            check();
            delPic.Visible = true;
            picturePre.Visible = true;
            openClose.Image = ((System.Drawing.Image)(Properties.Resources.closeIcon));
            this.Size = new System.Drawing.Size(953, this.Size.Height);
            listView1.Visible = true;
            listView1.Width = 188;
            loadimages();

        }
        private void close()
        {
            listView1.Items.Clear();
            imageList1.Images.Clear();
            delPic.Visible = false;
            picturePre.Visible = false;
            openClose.Image = ((System.Drawing.Image)(Properties.Resources.openIcon));

            this.Size = new System.Drawing.Size(pictureBox1.Width+100, this.Size.Height);
            listView1.Visible = false;
        
        }
        private void Delete()
        {
            try
            {

                if (listView1.Items.Count <= 0)
                {
                    return;
                }
                else
                {
                    GC.Collect();
                    Thread.Sleep(500);
                    intselectedindex = listView1.SelectedIndices[0];
                    File.Delete(files[intselectedindex]);

                }
               
                myPlayer.SoundLocation = appPath + "\\delete.wav";
                myPlayer.Play();
                loadimages();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
        }

        private void loadimages()
        {

            files.Clear();
            imageList1.Images.Clear();
            listView1.Clear();
            string[] part1 = null, part2 = null, part3 = null;

            part1 = Directory.GetFiles(p, "*.Jpg");
            part2 = Directory.GetFiles(p, "*.Jpeg");
            part3 = Directory.GetFiles(p, "*.Bmp");


            for (int i = 0; i < part1.Length; i++)
            {
                imageList1.Images.Add(Image.FromFile(part1[i]));
                listView1.Items.Add("", i);
                files.Add(part1[i]);

            }
            for (int i = 0; i < part2.Length; i++)
            {

                imageList1.Images.Add(Image.FromFile(part2[i]));
                listView1.Items.Add("", i);
                files.Add(part2[i]);

            }
            for (int i = 0; i < part3.Length; i++)
            {

                imageList1.Images.Add(Image.FromFile(part3[i]));
                listView1.Items.Add("", i);
                files.Add(part3[i]);

            }
            check();
            PhotoPlace.Text = p;
        }

        private void Up()
        {
            upDown.Image = ((System.Drawing.Image)(Properties.Resources.downIcon));

            this.Size = new System.Drawing.Size(this.Size.Width, 605);
        }

        private void Down()
        {
            upDown.Image = ((System.Drawing.Image)(Properties.Resources.upIcon));

            this.Size = new System.Drawing.Size(this.Size.Width, 691);

        }

        private void check()
        {
            if (imageList1.Images.Count <= 0)
            {
                delPic.Enabled = false;

            }
            else
            {
                delPic.Enabled = true;
            }
        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(p);
        }
        

        private void listView1_DoubleClick_1(object sender, EventArgs e)
        {
            /*intselectedindex = listView1.SelectedIndices[0];
            Process.Start("explorer.exe", @"/select, " + files[intselectedindex]);*/
            stopVideo();
            intselectedindex = listView1.SelectedIndices[0];
            FileInfo f = new FileInfo(files[intselectedindex]);
            String url = f.FullName.ToString();
            urlPicturebox = url;
            image = new Bitmap(url);
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
            //pictureBox1.Image = (Image)image;
            pictureBox1.Image = (Image)image;
            preImage = new Bitmap(urlPicturebox);
            buttonSave.Visible = true;
            chkFlipHorizontal.Visible = false;
            chkFlipVertical.Visible = false;  
        } 

        private void listView1_MouseClick(object sender, MouseEventArgs e)
        {
            Image inm=null;
            intselectedindex = listView1.SelectedIndices[0];
            FileInfo f=new FileInfo(files[intselectedindex]);
            inm=imageList1.Images[intselectedindex];
            toolTip1.Show("Image Name: "+f.Name.ToString()+"\nImage Type: "+f.Extension.ToString()+
                "\nImage Directary: " + f.Directory.ToString()+"\nImage Resolution: "+inm.HorizontalResolution.ToString()+
                 "X"+inm.VerticalResolution.ToString()+ "\nCreation Time: "+f.CreationTime.ToString()
                , listView1);
            
        }

        private void Main_KeyDown(object sender, KeyEventArgs e)

        {
            if (e.Control && e.KeyCode.ToString() == Keys.Enter.ToString())
            {
                TakePic();

            }
            else if (e.Control && e.KeyCode.ToString() == Keys.S.ToString())
            {
                Setting();

            }
            else if (e.KeyCode == Keys.F1)
            {
                About();
            }
            else if (e.KeyCode == Keys.Delete)
            {
                Delete();
            }
            else if (e.Control && e.KeyCode.ToString() == Keys.Right.ToString())
            {
                open();
            }
            else if (e.Control && e.KeyCode.ToString() == Keys.Left.ToString())
            {
                close();
            }
            else if (e.Control && e.KeyCode.ToString() == Keys.Up.ToString())
            {
                Up();
            }
            else if (e.Control && e.KeyCode.ToString() == Keys.Down.ToString())
            {
                Down();
            }

        }

        private void BroseF_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                PhotoPlace.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void pictureTakePic_Click(object sender, EventArgs e)
        {
            if (video == true)
            {
                TakePic();
            }
            else
            {
                startVideo();
                buttonSave.Visible = false;
                chkFlipHorizontal.Visible = true;
                chkFlipVertical.Visible = true;
            }
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            intselectedindex = listView1.SelectedIndices[0];
            FileInfo f = new FileInfo(files[intselectedindex]);
            String url = f.FullName.ToString();
            if (url == urlPicturebox)
            {
                MessageBox.Show("anh dang dung");
            }
            else
            {
                Delete();
            }

        }

        private void pictureBox2_Click_1(object sender, EventArgs e)
        {
            if (timer1.Enabled == true)
            {
                timer1.Enabled = false;
                close();
                delPic.Visible = false;

            }
            else
            {
                timer1.Enabled = true;
                delPic.Visible = true;
                open();
            }
        }

        private void pictureBox2_Click_2(object sender, EventArgs e)
        {
            if (timer2.Enabled == true)
            {
                timer2.Enabled = false;
                Up();

            }
            else
            {
                timer2.Enabled = true;
                Down();

            }
        }

        private void aboutCam_Click(object sender, EventArgs e)
        {
            About();
        }

        private void pictureBox2_Click_3(object sender, EventArgs e)
        {
            Exit();
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            Finalvideosource.Stop();
            Finalvideosource = new VideoCaptureDevice(Vidoedevices[comboBox1.SelectedIndex].MonikerString);
            Finalvideosource.NewFrame += new NewFrameEventHandler(Vidoedevice_newframe);
            Finalvideosource.Start();
            p = PhotoPlace.Text;
            f = Formats.Text;
            loadimages();
            MessageBox.Show("Settings Changed Successfully", " ", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void pictureTakePic_MouseHover(object sender, EventArgs e)
        {
            if (video == true)
            {
                toolTip1.Show("Take a picture", pictureTakePic);
            }
            else toolTip1.Show("start camera", pictureTakePic);
        }

        private void upDown_MouseHover(object sender, EventArgs e)
        {
            toolTip1.Show("Show Options", upDown);
        }

        private void openClose_MouseHover(object sender, EventArgs e)
        {
            toolTip1.Show("Show Pictures", openClose);
        }

        private void settingPic_MouseHover(object sender, EventArgs e)
        {
            toolTip1.Show("Change Setting", settingPic);
        }

        private void aboutCam_MouseHover(object sender, EventArgs e)
        {
            toolTip1.Show("About this program", aboutCam);
        }

        private void pictureBox2_MouseHover(object sender, EventArgs e)
        {
            toolTip1.Show("Exit", pictureBox2);
        }

        private void delPic_MouseHover(object sender, EventArgs e)
        {
            toolTip1.Show("delete Picture", delPic);
        }

        private void okButton_MouseHover(object sender, EventArgs e)
        {
            toolTip1.Show("OK", okButton);
        }

        private void buttonSave_MouseHover(object sender, EventArgs e)
        {
            toolTip1.Show("save picture", buttonSave);
        }

         private void timer3_Tick(object sender, EventArgs e)
        {
            pictureBox1.Refresh();
            //setting set = new setting();
             if (setting.defaul == true)
             {
                 image = new Bitmap(urlPicturebox);
                 pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                 pictureBox1.Image = (Image)Main.image;
                 setting.defaul = false;
             }
        }

         private void settingPic_Click(object sender, EventArgs e)
         {
             if (video == true)
             {
                 timer3.Enabled = false;
                 Setting();
             }
             else
             {
                 timer3.Enabled = true;
                 setting set = new setting();
                 set.Show();
                 timer3.Start();
             }
         }

         private void buttonSave_Click(object sender, EventArgs e)
         {
             TakePic();
         }

         private void button1_Click(object sender, EventArgs e)
         {
             image = preImage;
             pictureBox1.Refresh();
         }

         private void button2_Click(object sender, EventArgs e)
         {
             image = new Bitmap(urlPicturebox);
             pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
             //pictureBox1.Image = (Image)image;
             pictureBox1.Image = (Image)image;
         }
    }
}